package com.sumer.psychology.tag.domain.model;

import com.sumer.psychology.common.domain.model.ConcurrencySafeEntity;

import java.util.HashSet;
import java.util.Set;

/**
 * 可标记的实体
 * <p/>
 * User: zhenguang.zhu
 * Date: 2014/9/10
 * Time: 16:20
 */
public abstract class AbstractTaggedEntity extends ConcurrencySafeEntity implements Tagged {
    private Set<Tag> tags = new HashSet<>(0);
    private Set<Tag> removedTags = new HashSet<>(0);

    @Override
    public int tagCount() {
        return tags().size();
    }

    @Override
    public void replaceTags(Set<Tag> newTags) {
        beforeReplaceTags(newTags);

        setRemovedTags(newTags);
        tags().clear();
        setTags(newTags);

        afterReplaceTags();
    }

    protected Set<Tag> tags() {
        return tags;
    }

    protected Set<Tag> removedTags() {
        return removedTags;
    }

    protected void setTags(Set<Tag> tags) {
        if (tags == null) {
            tags().clear();
            return;
        }

        this.tags = tags;
    }

    /*
     * 设置删除的Tag
     */
    private void setRemovedTags(Set<Tag> newTags) {
        if (newTags == null) {
            removedTags = tags();
            return;
        }

        for (Tag oldTag : tags()) {
            if (!newTags.contains(oldTag)) {
                removedTags.add(oldTag);
            }
        }
    }

    /**
     * 替换标记后
     */
    protected abstract void afterReplaceTags();

    /**
     * 替换标记前
     */
    protected abstract void beforeReplaceTags(Set<Tag> tags);

    /**
     * 删除的标记
     *
     * @return count
     */
    public int removedTagCount() {
        return removedTags.size();
    }
}
